(function(factory){

    var nameSpace = 'field_5484916566399136200';
    if(!window[nameSpace]){
        var Builder = factory();
        window[nameSpace] = {
            instance: {}
        };
        window[nameSpace].init = function (options) {
            window[nameSpace].instance[options.privateId] = new Builder(options);
        };
        window[nameSpace].isNotNull = function (obj) {
            return true;
        };
    }
})(function(){
    /**
     * 正文组件构造函数
     * @param options
     * @constructor
     */
    function App(options) {
        var self = this;
        //初始化参数
        self.initParams(options);
        //初始化dom
        self.initDom();
        //事件
        self.events();
    };
    
    function isEmpty(obj) {
        if(obj === null || obj === "" || obj === undefined){
            return true;
        }
        return false;
    };
    function formatDataTableName(contentVal){
	
        if(isEmpty(contentVal)){
            return [];
        }

        try {
			 var tableName = contentVal.formdata.alldata.tableInfo.formmain.tableName;
			 return tableName;

        }catch (e) {  console.log(e); }
        return  null;
    };
	function formatDataFieldInfo(contentVal,fid){
	
        if(isEmpty(contentVal)){
            return [];
        }
        var fieldInfoA = contentVal.formdata.alldata.tableInfo.formmain.fieldInfo;

		var fieldInfo = fieldInfoA[fid];

        return  fieldInfo;
    };
    
    App.prototype = {
        initParams : function (options) {
            var self = this;
            self.adaptation = options.adaptation;
            self.privateId = options.privateId;
            self.messageObj = options.getData;
            self.preUrl = options.url_prefix;
        },
        initDom : function () {
            var self = this;
	
            dynamicLoading.css(self.preUrl + 'css/docUploadFormControls.css');
            self.appendChildDom();
        },
        events : function () {
            var self = this;
            // 监听是否数据刷新
            self.adaptation.ObserverEvent.listen('Event' + self.privateId, function() {
                self.messageObj = self.adaptation.childrenGetData(self.privateId);
                self.appendChildDom();
            });



        },
        appendChildDom : function () {
					

            var self = this;
			var fieldId = self.messageObj.id;

			//console.log('fieldId='+ fieldId);
            var showLabel = '附件';

			var tableName = formatDataTableName(self.messageObj);
      
			//console.log('tableName='+ tableName);

			var idFieldInfo = formatDataFieldInfo(self.messageObj,'field0001');

            var bizId = idFieldInfo.value;

			

			var docNameFieldInfo = formatDataFieldInfo(self.messageObj,'field0003');
            var docName = docNameFieldInfo.value;

            var docName2FieldInfo = formatDataFieldInfo(self.messageObj,'field0050');
            var docName2 = null;
            if (docName2FieldInfo)
            {
                docName2 = docName2FieldInfo.value;
            }


            function ajaxAttController(bizId,formDataId) {
				$.ajax({
					type : 'post',
					async : true,
					// 记得加随机数，不然如果ajax轮询请求会不执行
					url : encodeURI('/seeyon/ext/down1.do?method=index&bizId='+bizId+'&docName='+ docName+ '&docName2='+docName2+
                        '&datetime=' + Math.random()),
					dataType : 'json',
					contentType : 'application/json;charset=UTF-8',
					success : function(res) {
						if (res.success) {
							renderMultiBtn(self,res.data,formDataId)
						} 

					}
				});
			}


            var formDataId = null;
            var _privateId = self.privateId;
            if(self.messageObj.formdata.content){
                formDataId = self.messageObj.formdata.content.contentDataId;
		
            }
			
           ajaxAttController(bizId,formDataId);
          
        }
    };
    

    /**
     * 渲染为多个按钮的
     * @param self
     * @param fileList
     * @param formDataId
     */
    function renderMultiBtn(self,fileList,formDataId) {
        //渲染隐藏权限
    
        for(var i = 0;i < fileList.length; i++){
            var tempValue = fileList[i];
            if(!tempValue){
                continue;
            }
           
            var domStructure = '\
            <section class="doc_btn_box" id="doc_btn_box_' + self.privateId + '">\
                <div class="btn_content ' + self.privateId+ '" title="' + tempValue.DOCNAME + '">' + tempValue.DOCNAME + '</div>\
            </section>';
            var $domStructure = $(domStructure);
            $domStructure.attr("dataFormat",tempValue.dataFormat).attr("contentData",JSON.stringify(tempValue));
            $domStructure.click(function () {
                var contentData = $(this).attr("contentData");
                jumpFun(JSON.parse(contentData),formDataId,self.privateId);
            });
			 $('#' + self.privateId).append($domStructure);

        }

		
		 var domStructure = '\
        <iframe class="iframe4Download" style="display: none">\
           \</iframe>';
        var $domStructure = $(domStructure);
		$('#' + self.privateId).append($domStructure);
		
    }
    
    /**
     * 渲染预览
     * @param self
     */
    function renderPreview(self) {
        var showLabel = self.messageObj.display;
        var domStructure = '\
        <section class="doc_one_btn_box" id="doc_one_btn_box_' + self.privateId + '">\
            <div class="btn_content ' + self.privateId+ '" title="' + showLabel + '">' + showLabel + '</div>\
        </section>';
        var $domStructure = $(domStructure);
        $('#' + self.privateId).append($domStructure);
    }
    
    
/*
{
    "success":1,
    "data":[{
        "UPLOADTYPE":"localDownload",
        "MTPID":"04137e2f5fac97b5015fad48893d0524",
        "FTPPASS":null,
        "COMMORGIDENTY":null,
        "BIZID":"1530507724206_0_0",
        "COMMEDITIONID":null,
        "BLANK1":"0",
        "BLANK0":null,
        "BLANK3":null,
        "BLANK2":null,
        "DOCSIZE":29880,
        "COMMAPPID":null,
        "ATTACHMENTID":"1530507724206_0_0",
        "FTPNAME":null,
        "FTPPORT":null,
        "COMMCREATETIME":"2018-07-02 13:03:12",
        "COMMORGLEVEL":null,
        "SAVENAME":"1530507724206_0_0",
        "BIZTYPE":"????",
        "FTPSERVER":null,
        "DOCNAME":"1530507724206_0_0.doc",
        "COMMBUINESSORDER":null,
        "COMMCREATOR":"948a808e62df28b90162e3cde585175b",
        "DOCPATH":"/home/oafiles/jc6/upload/ForArchivesContent/2018-07-02/1530507724206_0_0.doc",
        "ISSECRET":"0",
        "COMMEDITIONNO":null,
        "DOCSUFFIX":"doc",
        "COMMCHANGENOTICE":null,
        "COMMRECORDIDENTY":null
    }]
}
*/
    function jumpFun(contentData,formDataId,_privateId) {//点击事件
		
        var title = contentData.DOCNAME;
        var FTPNAME = contentData.FTPNAME;
        var DOCPATH = contentData.DOCPATH;
        var FTPPORT = contentData.FTPPORT;
		var FTPSERVER = contentData.FTPSERVER;
		var ATTACHMENTID = contentData.ATTACHMENTID;
		var DOCSUFFIX = contentData.DOCSUFFIX;
		var url = encodeURI('/seeyon/ext/downproxy1.do?method=index&attId='+ATTACHMENTID +'&datetime=' + Math.random());

		if (DOCSUFFIX=='html'||DOCSUFFIX=='htm'||DOCSUFFIX=='jpg'||DOCSUFFIX=='png'||DOCSUFFIX=='bmp')
		{
            window.open(url, "_blank", "scrollbars=yes,resizable=1,modal=false,alwaysRaised=yes");
		} else 
		{
			document.querySelector('#' + _privateId + " .iframe4Download").src =url;
		}
    };
    
    var dynamicLoading = {
        css: function(path) {
            if(!path || path.length === 0) {
                throw new Error('argument "path" is required !');
            }
            var head = document.getElementsByTagName('head')[0];
            var link = document.createElement('link');
            link.href = path;
            link.rel = 'stylesheet';
            link.type = 'text/css';
            head.appendChild(link);
        },
        js: function(path) {
            if(!path || path.length === 0) {
                throw new Error('argument "path" is required !');
            }
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.src = path;
            script.type = 'text/javascript';
            head.appendChild(script);
        }
    };

    return App;
});